//
//  UIGridViewController.m
//  GridViewUsingTableView
//
//  Created by Manoj Babu on 26/09/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "UIGridViewController.h"
#import "UIGridViewCell.h"
#import "JSON.h"

#define FLICKER_API_KEY @"ENTER YOUR FLICEKER API KEY"

@interface UIGridViewController()
-(void)setupViewController;
@end

@implementation UIGridViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [data release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
}
*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [self loadData];
    [super viewDidLoad];
}


- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self setupViewController];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(void)loadData
{
    NSString *urlStr = @"http://api.flickr.com/services/rest/";
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
    NSString *postData = [NSString stringWithFormat:@"method=flickr.photos.search&api_key=%@&tags=birds&per_page=200&format=json&nojsoncallback=1",FLICKER_API_KEY];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:[postData dataUsingEncoding:NSUTF8StringEncoding]];
    NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
    _responseData = [[NSMutableData alloc] init];
    [connection start];
}
#pragma NSURLConnection delegate methods

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)tdata
{
    [_responseData appendData:tdata];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error      
{
    
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSString *responseString = [[NSString alloc] initWithData:_responseData
                                                     encoding:NSUTF8StringEncoding];
   // NSLog(@"Response data :- %@",responseString);
    NSDictionary *responseData = [responseString JSONValue];
    data = [[NSArray alloc] initWithArray:[[responseData objectForKey:@"photos"] objectForKey:@"photo"]];
    [gridView reloadData];
}


#pragma Private methods

-(void)setupViewController
{
    gridView = [[UIGridView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width , self.view.frame.size.height)];
    gridView.delegate = self;
    gridView.dataSource = self;
    [self.view addSubview:gridView];
}

#pragma UIGridView data source methods
-(NSUInteger)numberOfItemsInGridView:(UIGridView *)gridView
{
    return [data count];
}

-(UIGridViewCell *)gridView:(UIGridView *)tgridView cellForIndexAtGridPath:(UIGridPath *)gridPath
{
    //NSLog(@"Row :- %d, column :- %d, index :- %d",gridPath.row,gridPath.column, gridPath.index);
    UIGridViewCell *cell = nil;
    cell = [tgridView dequeueCellAtGridPath:gridPath];
    if(cell == nil)
        cell = [[[UIGridViewCell alloc] init] autorelease];
    //NSLog(@"Image :- %@",[[data objectAtIndex:gridPath.index] objectForKey:@"small_thumb"]);
    NSDictionary *photoDetails = [data objectAtIndex:gridPath.index];
    NSString *farm_id = [photoDetails objectForKey:@"farm"];
    NSString *server_id = [photoDetails objectForKey:@"server"];
    NSString *photo_id = [photoDetails objectForKey:@"id"];
    NSString *secret = [photoDetails objectForKey:@"secret"];
    NSString *url = [NSString stringWithFormat:@"http://farm%@.static.flickr.com/%@/%@_%@_s.jpg",farm_id,server_id,photo_id,secret];
    [cell loadCellAtIndex:gridPath.index withURL:url];
    //[cell loadCellAtIndex:gridPath.index withURL:nil];
    return cell;
}


#pragma UIGridView delegate methods

-(void)didSelectCellAtGridPath:(UIGridPath *)gridPath
{
    NSLog(@"Did select cell at index :- %d",gridPath.index);
}

@end
